#include "head.h"

typedef struct train_s {
  int len;
  char buf[1024];
} train_t;

int doWorker(int local_socket_fd) {
  while (1) {
    int fd,flag;
    int ret_recvmsg = recvMesg(local_socket_fd, &fd, &flag);
    ERROR_CHECK(ret_recvmsg, -1, "recvMesg in worker.c");
    if (flag == -1) {
      printf("child process %d is cleaning & exiting...\n", getpid());
      exit(0);
    }
    pid_t pid = getpid();
    printf("worker No.%d (PID = %d) is working...\n", fd, pid);

    sendBFile(fd);
    // working...
    close(fd);

    int ret_send = send(local_socket_fd, "123", 3, 0);
  }
  return 0;
}


int sendBFile(int net_fd) {
  char *fileName = "1.txt";
  int fileFd = open(fileName, O_RDWR);
  train_t train;
  memset(&train, 0, sizeof(train));

  struct stat fileStat;
  // 获得文件信息
  fstat(fileFd, &fileStat);

  // 发送文件长度
  send(net_fd, &fileStat.st_size, sizeof(off_t), MSG_NOSIGNAL);

  // train.len记录文件名长度,并将文件名放进train.buf
  memset(&train, 0, sizeof(train));
  train.len = strlen(fileName);
  memcpy(train.buf, fileName, train.len);

  // 发送文件名长度与文件名
  send(net_fd, &train, sizeof(int) + train.len, MSG_NOSIGNAL);

  sendfile(net_fd, fileFd, NULL, fileStat.st_size);
  printf("sending over\n");

  close(fileFd);
  return 0;
}
